import {Label, Table, createTableCell} from '@kintone/kintone-ui-component/esm/js';
import util from '../common/util';

export class ConfigTable {
  constructor(server, pluginConfig, tableCells) {
    this.pluginConfig = pluginConfig;
    this.server = server;
    this.table = new Table({
      columns: [
        {
          header: `${this.server.NAME}API返回值名称`,
          cell: () => createTableCell('label', 'label')
        },
        {
          header: '对应的kintone字段',
          cell: () => createTableCell('dropdown', 'dropdown'),
        }
      ],
      actionButtonsShown: false
    });

    // {xxx: {name:xx, kintoneFieldType: []}}
    this.tableCells = tableCells;
  }

  render() {
    const div = document.createElement('div');
    div.appendChild(new Label({text: `请设置用于保存${this.server.NAME}API返回结果的kintone字段`}).render());
    div.appendChild(this.table.render());
    return div;
  }

  /**
   * @param appFields  {FIELD_TYPE: {type: FIELD_TYPE, code: FIELD_CODE, label: FIELD_NAME}}
   */
  createTableCellValue(appFields) {
    const tableValue = [];

    if (typeof this.tableCells !== 'object' || typeof appFields !== 'object') {
      return tableValue;
    }

    for (const key in this.tableCells) {
      if (!this.tableCells.hasOwnProperty(key)
        || !this.tableCells[key].hasOwnProperty('name')
        || !this.tableCells[key].hasOwnProperty('kintoneFieldType')) {
        continue;
      }

      const cellLabelValue = {text: this.tableCells[key].name};
      const cellDropdownValue = {
        items: [{label: '--------', value: ''}],
        value: `${this.server.ID}_${key}` in this.pluginConfig ? this.pluginConfig[`${this.server.ID}_${key}`] : ''
      };
      const validKintoneFieldType = this.tableCells[key].kintoneFieldType;
      validKintoneFieldType.forEach(fieldType => {
        if (fieldType in appFields) {
          appFields[fieldType].forEach(field => {
            cellDropdownValue.items.push({label: field.label, value: field.code});
          });
        }
      });
      tableValue.push({label: cellLabelValue, dropdown: cellDropdownValue});
    }

    return tableValue;
  }

  /**
   * @param appFields  {FIELD_TYPE: {type: FIELD_TYPE, code: FIELD_CODE, label: FIELD_NAME}}
   */
  setValue(appFields) {
    const tableValue = this.createTableCellValue(appFields);
    this.table.setValue(tableValue);
  }

  getValue() {
    const values = {};
    const tableValue = this.table.getValue();
    Object.keys(this.tableCells).forEach((key, index) => {
      values[`${this.server.ID}_${key}`] = tableValue[index].dropdown.value;
    });
    return values;
  }

  checkDuplicateValue() {
    const tableValue = this.table.getValue();
    const tableCellsKeys = Object.keys(this.tableCells);
    for (let i = 0; i < tableCellsKeys.length; i++) {
      if (util.isEmptyString(tableValue[i].dropdown.value)) {
        continue;
      }

      for (let j = i + 1; j < tableCellsKeys.length; j++) {
        if (util.isEmptyString(tableValue[j].dropdown.value)) {
          continue;
        }

        if (tableValue[j].dropdown.value === tableValue[i].dropdown.value) {
          return `"${this.tableCells[tableCellsKeys[i]].name}" 和 "${this.tableCells[tableCellsKeys[j]].name}" 的值相同，请重新选择`;
        }
      }
    }
    return '';
  }
}